package com.hsq.ndmall.wx.service;

import com.hsq.ndmall.common.utils.ListFromEntity2VoUtils;
import com.hsq.ndmall.common.utils.R;
import com.hsq.ndmall.wx.feign.index.MallFeign;
import com.hsq.ndmall.wx.feign.index.PromotionFeign;
import com.hsq.ndmall.wx.vo.brand.BrandHomeVo;
import com.hsq.ndmall.wx.feign.index.ProductFeign;
import com.hsq.ndmall.wx.vo.category.CategoryHomeVo;
import com.hsq.ndmall.wx.vo.category.FloorHomeVo;
import com.hsq.ndmall.wx.vo.goods.NewGoodsVo;
import com.hsq.ndmall.wx.vo.groupon.GrouponHomeVo;
import com.hsq.ndmall.wx.vo.mall.TopicList;
import com.hsq.ndmall.wx.vo.promotion.AdHomeVo;
import com.hsq.ndmall.wx.vo.promotion.CouponHomeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName IndexService.java
 * @Description TODO  小程序首页
 * @createTime 2021年08月11日 22:53:00
 */
@Service
@Slf4j
public class IndexService {

    @Resource
    private ProductFeign productFeign;

    @Autowired
    private PromotionFeign promotionFeign;

    @Autowired
    private MallFeign mallFeign;

    @Cacheable(cacheNames = "wx-api-service" ,keyGenerator = "myRedis")
    public Map findIndexData() {
        Map resultMap = new HashMap<String, List>();
        long beginTime = System.currentTimeMillis();
        listProduct(resultMap);   // 单线程调用
//        // 创建一个线程池
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 9, 10, TimeUnit.SECONDS, new SynchronousQueue<>());
//        listProductCopy(resultMap, threadPoolExecutor);   // 多线程调用
//        // 关闭线程池
//        if (!threadPoolExecutor.isShutdown()) {
//            threadPoolExecutor.shutdown();
//        }
        long endTime = System.currentTimeMillis();
        System.out.println("执行一共用了：" + (endTime - beginTime) + "时间");
        return resultMap;

    }

    private void listProduct(Map resultMap) {
        Map paramMap = new HashMap<String, String>();
        //TODO  1.商品服务中的brand（品牌制造商直供）
        paramMap.put("page", 1);
        paramMap.put("limit", 4);
        R brandR = productFeign.listBrand(paramMap);
        List<Map> productList = (List<Map>) ((Map) brandR.get("page")).get("list");
        List<BrandHomeVo> brandHomeVoList = ListFromEntity2VoUtils.entity2Vo(productList, BrandHomeVo.class);
        resultMap.put("brandList", brandHomeVoList);

        // 清空
        paramMap.clear();


        //TODO   2.商品服务中的channel（ category:一级分类 ）
        paramMap.put("sort", "add_time");
        paramMap.put("order", "desc");
        paramMap.put("level", "L1");
//        R channelR = productFeign.listChannel(paramMap);
//        List<Map> channelList = (List<Map>) ((Map) (channelR.get("page"))).get("list");
        R listChannelTest = productFeign.listChannelTest();
        List<Map> channelList = (List<Map>) listChannelTest.get("channel");
        List<CategoryHomeVo> categoryHomeVoList = ListFromEntity2VoUtils.entity2Vo(channelList, CategoryHomeVo.class);
        resultMap.put("channel", categoryHomeVoList);


        //TODO  3.newGoodsList（新品首发:6个）----本来：营销库中获取   现在：产库库中获取
        // 清空
        paramMap.clear();
        paramMap.put("page", 1);
        paramMap.put("limit", 6);
        paramMap.put("sort", "add_time");
        paramMap.put("order", "desc");
        paramMap.put("isNew", "1"); // 1 代表是首发
        R listNewGoodsR = productFeign.listNewGoods(paramMap);
        List<Map> newGoodList = (List<Map>) ((Map) listNewGoodsR.get("page")).get("list");
        List<NewGoodsVo> newGoodsVos = ListFromEntity2VoUtils.entity2Vo(newGoodList, NewGoodsVo.class);
        resultMap.put("newGoodsList", newGoodsVos);


        //TODO  4.GoodsList（人气推荐:6个）
        paramMap.clear();
        paramMap.put("page", 1);
        paramMap.put("limit", 6);
        paramMap.put("sort", "add_time");
        paramMap.put("order", "desc");
        paramMap.put("isHot", "1");  // 1代表是人气推荐
        R listHotGoodsR = productFeign.listNewGoods(paramMap);
        List<Map> hotGoodList = (List<Map>) ((Map) listHotGoodsR.get("page")).get("list");
        List<NewGoodsVo> hotGoodsVos = ListFromEntity2VoUtils.entity2Vo(hotGoodList, NewGoodsVo.class);
        resultMap.put("hotGoodsList", hotGoodsVos);


        //TODO 5.floorList（4个分类-4个商品）
        paramMap.clear();
        R floorGoodsListR = productFeign.floorGoodsList(1, 4);
        List<Map> floorList = (List<Map>) ((Map) floorGoodsListR.get("page")).get("list");
        List<FloorHomeVo> floorHomeVoList = ListFromEntity2VoUtils.entity2Vo(floorList, FloorHomeVo.class);
        List<FloorHomeVo> list = new ArrayList<>();
        for (FloorHomeVo floorHomeVo : floorHomeVoList) {

            for (Map floor : floorList) {
                FloorHomeVo floorHomeVo1 = new FloorHomeVo();
                List<Map> floorGoodsList = (List<Map>) floor.get("goodsList");
                List<NewGoodsVo> floorGoodsVoList = ListFromEntity2VoUtils.entity2Vo(floorGoodsList, NewGoodsVo.class);
                floorHomeVo1.setGoodsList(floorGoodsVoList);
                list.add(floorHomeVo1);
            }
        }
        int i = 0;
        for (FloorHomeVo floorHomeVo : floorHomeVoList) {
            floorHomeVo.setGoodsList(list.get(i).getGoodsList());
            i++;
        }


        resultMap.put("floorGoodsList", floorHomeVoList);

        //TODO 一、营销推广微服务
        //TODO 6.banner（3个）  活动轮播
        paramMap.clear();
        paramMap.put("page", 1);
        paramMap.put("limit", 3);
        R listBanner = promotionFeign.listBanner(paramMap);
        List<Map> bannerList = (List<Map>) ((Map) listBanner.get("page")).get("list");
        List<AdHomeVo> adHomeVos = ListFromEntity2VoUtils.entity2Vo(bannerList, AdHomeVo.class);
        resultMap.put("banner", adHomeVos);

        //TODO 7.grouponList（4个）   团购专区
        paramMap.clear();
        R listGroupon = promotionFeign.listGroupon(paramMap);
        List<Map> grouponList = (List<Map>) listGroupon.get("page");
        List<GrouponHomeVo> grouponHomeVos = ListFromEntity2VoUtils.entity2Vo(grouponList, GrouponHomeVo.class);
        resultMap.put("grouponList", grouponHomeVos);


        //TODO 8.couponList（4个）    优惠券微服务
        paramMap.clear();
        paramMap.put("page", 1);
        paramMap.put("limit", 3);
        R listCoupon = promotionFeign.listCoupon(paramMap);
        List<Map> couponList = (List<Map>) ((Map) listCoupon.get("page")).get("list");
        List<CouponHomeVo> couponHomeVos = ListFromEntity2VoUtils.entity2Vo(couponList, CouponHomeVo.class);
        resultMap.put("couponList", couponHomeVos);


        //TODO 9.topicList（4个） 四、商城微服务服务
        paramMap.clear();
        paramMap.put("page", 1);
        paramMap.put("limit", 4);
        R listTopic = mallFeign.listTopic(paramMap);
        List<Map> topicList = (List<Map>) ((Map) listTopic.get("page")).get("list");
        List<TopicList> topicLists = ListFromEntity2VoUtils.entity2Vo(topicList, TopicList.class);
        resultMap.put("topicList", topicLists);
    }


    //TODO 多线程时，存在BUG，获取不了值
    private void listProductCopy(Map resultMap, ThreadPoolExecutor threadPoolExecutor) {
        // 定义一个map对象
        Map paramMap = new ConcurrentHashMap<String, String>();
        //TODO  1.商品服务中的brand（品牌制造商直供）
        paramMap.put("page", 1);
        paramMap.put("limit", 4);
        Callable<R> brandCallable = () -> {
            return productFeign.listBrand(paramMap);
        };//lambda
        //Future<R> brandFuture = threadPoolExecutor.submit(brandCallable);
        Future<R> brandFuture = threadPoolExecutor.submit(brandCallable);

        //TODO   2.商品服务中的channel（ category:一级分类 ）
        paramMap.clear();  // 清空map集合
        paramMap.put("sort", "add_time");
        paramMap.put("order", "desc");
        paramMap.put("level", "L1");
        Callable<R> channelCallable = () -> {
            return productFeign.listChannelTest();
        };
        Future<R> channelFuture = threadPoolExecutor.submit(channelCallable);

//        //TODO  3.newGoodsList（新品首发:6个）----本来：营销库中获取   现在：产库库中获取
//        // 清空
//        paramMap.clear();
//        paramMap.put("page", 1);
//        paramMap.put("limit", 6);
//        paramMap.put("sort", "add_time");
//        paramMap.put("order", "desc");
//        paramMap.put("isNew", "1"); // 1 代表是首发
//        Callable<R> newGoodsCallable = () -> {
//            return productFeign.listNewGoods(paramMap);
//        };
//        Future<R> newGoodsFuture = threadPoolExecutor.submit(newGoodsCallable);
//
//        //TODO  4.GoodsList（人气推荐:6个）
//        paramMap.clear();
//        paramMap.put("page", 1);
//        paramMap.put("limit", 6);
//        paramMap.put("sort", "add_time");
//        paramMap.put("order", "desc");
//        paramMap.put("isHot", "1");  // 1代表是人气推荐
//        Callable<R> HotGoodsCallable = () -> {
//            return productFeign.listNewGoods(paramMap);
//        };
//        Future<R> HotGoodsFuture = threadPoolExecutor.submit(HotGoodsCallable);
//
//        //TODO 一、营销推广微服务
//        //TODO 6.banner（3个）  活动轮播
//        paramMap.clear();
//        paramMap.put("page", 1);
//        paramMap.put("limit", 3);
//        Callable<R> bannerCallable = () -> {
//            return promotionFeign.listBanner(paramMap);
//        };
//        Future<R> bannerFuture = threadPoolExecutor.submit(bannerCallable);
//
//
//        //TODO 7.grouponList（4个）   团购专区
//        paramMap.clear();
//        Callable<R> grouponListCallable = () -> {
//            return promotionFeign.listGroupon(paramMap);
//        };
//        Future<R> grouponListFuture = threadPoolExecutor.submit(grouponListCallable);
//
//        //TODO 8.couponList（4个）    优惠券微服务
//        paramMap.clear();
//        paramMap.put("page", 1);
//        paramMap.put("limit", 3);
//        Callable<R> listCouponCallable = () -> {
//            return promotionFeign.listCoupon(paramMap);
//        };
//        Future<R> listCouponFuture = threadPoolExecutor.submit(listCouponCallable);
//
//        //TODO 9.topicList（4个） 四、商城微服务服务
//        paramMap.clear();
//        paramMap.put("page", 1);
//        paramMap.put("limit", 4);
//        Callable<R> topicListCallable = () -> {
//            return mallFeign.listTopic(paramMap);
//        };
//        Future<R> topicListFuture = threadPoolExecutor.submit(topicListCallable);
//
        R brandR = null;
        // 获取值

        try {
            // TODO 1.商品服务中的brand
            brandR = brandFuture.get();
            log.info("channel===>{}", brandR);
            List<Map> productList = (List<Map>) ((Map) brandR.get("page")).get("list");
            List<BrandHomeVo> brandHomeVoList = ListFromEntity2VoUtils.entity2Vo(productList, BrandHomeVo.class);
            resultMap.put("brandList", brandHomeVoList);

            //TODO 2.商品服务中的channel（ category:一级分类 ）
            R listChannelTest = channelFuture.get();
            List<Map> channelList = (List<Map>) listChannelTest.get("channel");
            List<CategoryHomeVo> categoryHomeVoList = ListFromEntity2VoUtils.entity2Vo(channelList, CategoryHomeVo.class);
            resultMap.put("channel", categoryHomeVoList);

//            //TODO  3.newGoodsList（新品首发:6个）----本来：营销库中获取   现在：产库库中获取
//            R listNewGoodsR = newGoodsFuture.get();
//            List<Map> newGoodList = (List<Map>) ((Map) listNewGoodsR.get("page")).get("list");
//            List<NewGoodsVo> newGoodsVos = ListFromEntity2VoUtils.entity2Vo(newGoodList, NewGoodsVo.class);
//            resultMap.put("newGoodsList", newGoodsVos);
//
//            //TODO  4.GoodsList（人气推荐:6个）
//            R listHotGoodsR = HotGoodsFuture.get();
//            List<Map> hotGoodList = (List<Map>) ((Map) listHotGoodsR.get("page")).get("list");
//            List<NewGoodsVo> hotGoodsVos = ListFromEntity2VoUtils.entity2Vo(hotGoodList, NewGoodsVo.class);
//            resultMap.put("hotGoodsList", hotGoodsVos);
//
//            //TODO 一、营销推广微服务
//            //TODO 6.banner（3个）  活动轮播
//            R listBanner = bannerFuture.get();
//            List<Map> bannerList = (List<Map>) ((Map) listBanner.get("page")).get("list");
//            List<AdHomeVo> adHomeVos = ListFromEntity2VoUtils.entity2Vo(bannerList, AdHomeVo.class);
//            resultMap.put("banner", adHomeVos);
//
//            //TODO 7.grouponList（4个）   团购专区
//            R listGroupon = grouponListFuture.get();
//            List<Map> grouponList = (List<Map>) ((Map) listGroupon.get("page")).get("list");
//            List<GrouponHomeVo> grouponHomeVos = ListFromEntity2VoUtils.entity2Vo(grouponList, GrouponHomeVo.class);
//            resultMap.put("grouponList", grouponHomeVos);
//
//            //TODO 8.couponList（4个）    优惠券微服务
//            R listCoupon = listCouponFuture.get();
//            List<Map> couponList = (List<Map>) ((Map) listCoupon.get("page")).get("list");
//            List<CouponHomeVo> couponHomeVos = ListFromEntity2VoUtils.entity2Vo(couponList, CouponHomeVo.class);
//            resultMap.put("couponList", couponHomeVos);
//
//            //TODO 9.topicList（4个） 四、商城微服务服务
//            R listTopic = topicListFuture.get();
//            List<Map> topicList = (List<Map>) ((Map) listTopic.get("page")).get("list");
//            List<TopicList> topicLists = ListFromEntity2VoUtils.entity2Vo(topicList, TopicList.class);
//            resultMap.put("topicList", topicLists);


        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("1异常了{}", e);
        } catch (ExecutionException e) {
            e.printStackTrace();
            log.info("2异常了{}", e);
        }

    }

}
